<template>
  <el-card class="appointment-card" shadow="hover">
    <div class="page-title">线上预约登记</div>
    <el-tabs v-model="activeTab" class="tab-container">
      <el-tab-pane label="待安排" name="tab1"></el-tab-pane>
      <el-tab-pane label="已安排" name="tab2"></el-tab-pane>
    </el-tabs>

    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入学生姓名/账号/学号/联系电话关键词查询"
        class="search-input"
        clearable
        @input="handleInput"
        @clear="resetSearch"
      />
      <el-button type="primary" @click="handleSearch" :disabled="!searchKeyword">查询</el-button>
      <el-button @click="resetSearch" :disabled="!hasSearched" class="ml-2">返回</el-button>
    </div>

    <!-- 待安排表格 -->
    <el-table
      v-if="activeTab === 'tab1'"
      ref="tableRef"
      :data="paginatedData"
      border
      style="width: 100%; margin-top: 20px"
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号" width="70"></el-table-column>
      <el-table-column prop="name" label="学生姓名"></el-table-column>
      <el-table-column prop="account" label="账号/学号"></el-table-column>
      <el-table-column prop="scale1" label="心理量表1"></el-table-column>
      <el-table-column prop="scale2" label="心理量表2"></el-table-column>
      <el-table-column prop="college" label="学院"></el-table-column>
      <el-table-column prop="counselor" label="责任辅导员"></el-table-column>
      <el-table-column prop="phone" label="联系电话"></el-table-column>
      <el-table-column prop="channel" label="预约渠道"></el-table-column>
      <el-table-column prop="operation" label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleArrange(scope.row)">安排</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 已安排表格 -->
    <el-table
      v-else
      :data="paginatedData"
      border
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号" width="70"></el-table-column>
      <el-table-column prop="name" label="学生姓名"></el-table-column>
      <el-table-column prop="account" label="账号/学号"></el-table-column>
      <el-table-column prop="scale1" label="心理量表1"></el-table-column>
      <el-table-column prop="scale2" label="心理量表2"></el-table-column>
      <el-table-column prop="college" label="学院"></el-table-column>
      <el-table-column prop="counselor" label="责任辅导员"></el-table-column>
      <el-table-column prop="phone" label="联系电话"></el-table-column>
      <el-table-column prop="channel" label="预约渠道"></el-table-column>
      <el-table-column prop="consult" label="咨询师"></el-table-column>
      <el-table-column prop="arrangeTime" label="安排时间" width="180"></el-table-column>
      <el-table-column prop="location" label="咨询地点"></el-table-column>
      <el-table-column prop="operation" label="操作">
        <template #default="scope">
          <el-button type="text" disabled>已安排</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredData.length"
      class="pagination"
    >
      <template #total>总共 {{ filteredData.length }} 个</template>
    </el-pagination>

    <div class="footer-actions" v-if="activeTab === 'tab1'">
      <el-button
        type="primary"
        @click="handleBatchArrange"
        :disabled="!selectedRows.length"
        style="margin-top: 20px"
      >
        批量安排
      </el-button>
    </div>

    <!-- 咨询师安排表单 -->
    <el-dialog v-model="dialogVisible" :title="isBatch ? '批量咨询师安排' : '咨询师安排'" width="50%">
      <el-form :model="arrangeForm" :rules="rules" ref="arrangeFormRef" label-width="120px">
        <el-form-item label="咨询师姓名" prop="counselorId">
          <el-select
            v-model="arrangeForm.counselorId"
            placeholder="请选择咨询师"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in counselorOptions"
              :key="item.id"
              :label="`${item.name} (${item.phone})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安排时间" prop="arrangeTime">
          <el-date-picker
            v-model="arrangeForm.arrangeTime"
            type="datetime"
            placeholder="请选择安排时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="咨询地点" prop="location">
          <el-input
            v-model="arrangeForm.location"
            placeholder="请输入咨询地点"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmArrange"
        >
          提交
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick } from 'vue';
import { getAppointmentData } from '../../api/mock';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';

const activeTab = ref('tab1');
const searchKeyword = ref('');
const searchValue = ref('');
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const dialogVisible = ref(false);
const isBatch = ref(false);
const arrangeFormRef = ref<FormInstance>();
const tableRef = ref(null);

// 待安排和已安排的数据
const pendingData = ref([]);
const arrangedData = ref([]);

// 当前操作的行数据
const currentRow = ref(null);

// 模拟咨询师选项数据
const counselorOptions = ref([
  { id: 1, name: '王瑶', phone: '17780104153' },
  { id: 2, name: '庄凯茜', phone: '13800138002' },
  { id: 3, name: '向珈君', phone: '13800138003' },
  { id: 4, name: '李欣宇', phone: '13800138004' }
]);

const arrangeForm = reactive({
  counselorId: '',
  arrangeTime: null,
  location: ''
});

const rules = reactive<FormRules>({
  counselorId: [
    { required: true, message: '请选择咨询师', trigger: 'change' }
  ],
  arrangeTime: [
    { required: true, message: '请选择安排时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入咨询地点', trigger: 'blur' }
  ]
});

// 记录是否进行过搜索
const hasSearched = ref(false);
// 选中的行
const selectedRows = ref([]);

// 获取数据
const fetchData = async () => {
  try {
    const res = await getAppointmentData();
    if (res.status) {
      tableData.value = res.data.tableData;
      // 根据status字段分离数据
      pendingData.value = res.data.tableData.filter(item => item.status === 'pending');
      arrangedData.value = res.data.tableData.filter(item => item.status === 'arranged');

      // 重新计算序号
      updateSequenceNumbers();
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取预约数据失败');
  }
};

// 更新序号
const updateSequenceNumbers = () => {
  pendingData.value.forEach((item, index) => {
    item.id = index + 1;
  });
  arrangedData.value.forEach((item, index) => {
    item.id = index + 1;
  });
};

fetchData();

// 过滤数据（支持关键词筛选）
const filteredData = computed(() => {
  const sourceData = activeTab.value === 'tab1' ? pendingData.value : arrangedData.value;
  if (!hasSearched.value) return sourceData;

  const keyword = searchKeyword.value.toLowerCase();
  return sourceData.filter(item => {
    // 关键词匹配姓名/学号/电话
    return (
      item.name?.toLowerCase().includes(keyword) ||
      item.account?.toLowerCase().includes(keyword) ||
      item.phone?.toLowerCase().includes(keyword)
    );
  });
});

// 分页数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

const handleSearch = () => {
  currentPage.value = 1;
  hasSearched.value = true;
};

// 重置搜索状态
const resetSearch = () => {
  searchKeyword.value = '';
  searchValue.value = '';
  currentPage.value = 1;
  hasSearched.value = false;
  tableRef.value?.clearSelection();
};

// 监听输入变化
const handleInput = () => {
  if (!searchKeyword.value.trim()) {
    resetSearch();
  }
};

// 监听表格选中变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

const handleArrange = (row: any) => {
  isBatch.value = false;
  currentRow.value = row;
  dialogVisible.value = true;

  // 重置表单
  Object.assign(arrangeForm, {
    counselorId: '',
    arrangeTime: null,
    location: ''
  });
};

const handleBatchArrange = () => {
  // 检查是否有待安排的选中项
  const pendingSelected = selectedRows.value.filter(item => item.status === 'pending');
  if (pendingSelected.length === 0) {
    ElMessage.warning('请选择待安排的记录');
    return;
  }

  ElMessageBox.confirm(`确定要批量安排选中的 ${pendingSelected.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isBatch.value = true;
    dialogVisible.value = true;
    // 重置表单
    Object.assign(arrangeForm, {
      counselorId: '',
      arrangeTime: null,
      location: ''
    });
  }).catch(() => {
    // 用户取消
  });
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

const confirmArrange = async () => {
  if (!arrangeFormRef.value) return;

  try {
    // 表单验证
    await arrangeFormRef.value.validate();

    if (isBatch.value) {
      // 批量安排逻辑
      const pendingSelected = selectedRows.value.filter(item => item.status === 'pending');
      const arrangedCount = pendingSelected.length;

      const consultant = counselorOptions.value.find(c => c.id === arrangeForm.counselorId);

      // 先收集所有要移动的数据
      const toBeMoved = [];

      pendingSelected.forEach((item: any) => {
        item.status = 'arranged';
        item.consult = consultant ? `${consultant.name} (${consultant.phone})` : '';
        item.arrangeTime = arrangeForm.arrangeTime ? formatDateTime(arrangeForm.arrangeTime) : '';
        item.location = arrangeForm.location;
        item.counselorId = arrangeForm.counselorId;

        toBeMoved.push(item);
      });

      // 从待安排移除
      pendingData.value = pendingData.value.filter(item =>
        !pendingSelected.some(selected => selected.id === item.id)
      );

      // 添加到已安排
      arrangedData.value = [...arrangedData.value, ...toBeMoved];

      // 更新序号
      updateSequenceNumbers();

      ElMessage.success(`成功批量安排 ${arrangedCount} 条记录`);
      nextTick(() => {
        tableRef.value?.clearSelection();
      });
    } else {
      // 单个安排逻辑
      if (currentRow.value) {
        const consultant = counselorOptions.value.find(c => c.id === arrangeForm.counselorId);

        // 更新行数据
        currentRow.value.status = 'arranged';
        currentRow.value.consult = consultant ? `${consultant.name} (${consultant.phone})` : '';
        currentRow.value.arrangeTime = arrangeForm.arrangeTime ? formatDateTime(arrangeForm.arrangeTime) : '';
        currentRow.value.location = arrangeForm.location;
        currentRow.value.counselorId = arrangeForm.counselorId;

        // 从待安排移除
        pendingData.value = pendingData.value.filter(item => item.id !== currentRow.value.id);

        // 添加到已安排
        arrangedData.value = [...arrangedData.value, currentRow.value];

        // 更新序号
        updateSequenceNumbers();

        ElMessage.success('安排成功');
      } else {
        ElMessage.warning('请先选择一条记录');
      }
    }

    dialogVisible.value = false;
  } catch (error) {
    console.log('表单验证失败', error);
  }
};

// 格式化日期时间
const formatDateTime = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
};

// 行样式：双量表分数低于60分时高亮
const tableRowClassName = ({ row }: { row: any }) => {
  const scale1 = parseInt(row.scale1.replace('分', ''));
  const scale2 = parseInt(row.scale2.replace('分', ''));
  if (scale1 < 60 && scale2 < 60) {
    return 'highlight-row';
  }
  return '';
};
</script>

<style scoped>
.appointment-card {
  margin: 20px;
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.tab-container {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

::v-deep .highlight-row {
  background-color: #fef0f0;
}

::v-deep .highlight-row td {
  color: #f56c6c;
}

::v-deep .el-form-item__label {
  font-weight: bold;
}
</style>